﻿///<reference path="~/Scripts/jquery-1.6.2.min.js" />
(function ($) {
    jQuery.fn.doubleSelectBox = function (options) {
        var self = $(this);
        if (typeof options == "string") {
            var commandArgs = [self.data('doubleSelectBox')].concat([].slice.call(arguments, 1));
            func[options].apply(this, commandArgs);
            return self;
        }

        var opts = $.extend({}, defaults, options);
        self.data('doubleSelectBox', opts);

        var param = [];
        param.push(opts);

        $(opts.addTag, self).bind(opts.event, function () {
            func.remove.apply(self, param);
        });
        $(opts.allTag, self).bind(opts.event, function () {
            func.add.apply(self, param);
        });
        return self;
    };

    var defaults = {
        event: 'dblclick',
        addTag: 'select:first',
        allTag: 'select:eq(1)',
        allValue: '' //如果遇到这个Value，listbox会查出适当的反应
    };

    var func = {
        "add": function (opts) {
            var from = $(opts.allTag, $(this)), to = $(opts.addTag, $(this));
            var itemAll = assign(opts, from, to);
            if (itemAll) {
                var set = [];
                $(to).children("[value!=" + itemAll + "]").each(function () {
                    set.push("<option value='" + $(this).val() + "'>" + $(this).text() + "</option>");
                }).remove();
                from.append(set.join('')).attr("disabled", true);
            }
        },
        "remove": function (opts) {
            var from = $(opts.addTag, $(this)), to = $(opts.allTag, $(this));

            if (assign(opts, from, to) !== false) {
                $(to).attr("disabled", false);
            }
        }

    };  //if selected allItem, it return the AllItem's Text, else return false.
    function assign(opts, from, to) {
        var selectedItems = from.val() || [];

        //include allItem?
        var selectedItem = hasAllItem(selectedItems, opts);

        if (selectedItem !== false) {
            selectedItems = [];
            selectedItems.push(selectedItem);
        }

        var selectedElements = $("option[value=" + selectedItems.join("],option[value=") + "]", from);
        var appendSet = [];
        $.each(selectedElements, function () {
            appendSet.push("<option value='" + $(this).val() + "'>" + $(this).text() + "</option>");
        });
        to.append(appendSet.join(''));
        selectedElements.remove();
        return selectedItem;
    }

    function hasAllItem(selectedItems, opts) {
        for (var i = 0; i < selectedItems.length; i++) {
            var item = selectedItems[i];
            if (opts.allValue == item)
                return item;
        }
        return false;
    }



})($);